<template>
  <div class="reports-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h3>测试报告</h3>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left-section">
        <h3>报告列表</h3>
        <div class="device-summary">
          <span class="summary-text">
            共 {{ filteredReports.length }} 个报告
          </span>
        </div>
      </div>

      <div class="right-section">
        <el-input
          v-model="reportFilter"
          placeholder="搜索报告..."
          clearable
          class="search-input"
        >
          <template #prefix>
            <SvgIcon name="search" size="16px" />
          </template>
        </el-input>

        <el-button-group class="filter-buttons">
          <el-button
            :type="reportStatusFilter === 'all' ? 'primary' : 'default'"
            size="default"
            @click="setReportStatusFilter('all')"
          >
            全部
          </el-button>
          <el-button
            :type="reportStatusFilter === 'completed' ? 'success' : 'default'"
            size="default"
            @click="setReportStatusFilter('completed')"
          >
            已完成
          </el-button>
          <el-button
            :type="reportStatusFilter === 'running' ? 'warning' : 'default'"
            size="default"
            @click="setReportStatusFilter('running')"
          >
            运行中
          </el-button>
        </el-button-group>

        <el-button
          type="primary"
          size="default"
          @click="refreshReports"
          :loading="loading"
        >
          <SvgIcon name="reload" size="18px" />
          <span style="margin-left: 6px">刷新</span>
        </el-button>
      </div>
    </div>

    <!-- 报告统计信息 -->
    <div class="device-stats">
      <span class="stat-item">
        已完成:
        <span class="stat-number success">{{ completedCount }}</span>
      </span>
      <span class="stat-item">
        运行中:
        <span class="stat-number warning">{{ runningCount }}</span>
      </span>
      <span class="stat-item">
        总数:
        <span class="stat-number total">{{ reports.length }}</span>
      </span>
    </div>

    <!-- 报告列表 -->
    <div class="reports-content" v-loading="loading">
      <el-table
        :data="paginatedReports"
        style="width: 100%"
        :row-class-name="getRowClassName"
        @row-click="handleRowClick"
        :empty-text="''"
        height="calc(100vh - 290px)"
      >
        <el-table-column
          prop="user_email"
          label="执行者"
          width="200"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.user_email ? scope.row.user_email.split('@')[0] : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="report_id"
          label="报告ID"
          width="200"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="device_id"
          label="设备ID"
          width="200"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="package_name"
          label="应用包名"
          min-width="140"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="app_version"
          label="版本"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="test_start_time"
          label="开始时间"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="test_duration"
          label="测试时长"
          width="100"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.test_duration }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="crash_count"
          label="崩溃数"
          width="80"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.crash_count > 0 ? 'danger' : 'success'"
              size="small"
            >
              {{ scope.row.crash_count }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="coverage_rate"
          label="覆盖率"
          width="80"
          align="center"
        >
          <template #default="scope">
            <span
              class="coverage-rate"
              :style="{
                color:
                  scope.row.coverage_rate >= 80
                    ? '#67c23a'
                    : scope.row.coverage_rate >= 60
                    ? '#e6a23c'
                    : '#f56c6c',
                fontWeight: '600',
              }"
            >
              {{ Math.round(scope.row.coverage_rate || 0) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.stop="viewReportDetail(scope.row.report_id)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div v-if="filteredReports.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无测试报告" :image-size="100">
          <template #description>
            <div class="empty-description" style="margin-top: 200px">
              <p>当前没有找到符合条件的测试报告</p>
              <p>请尝试：</p>
              <ul>
                <li>检查筛选条件</li>
                <li>清空搜索关键词</li>
                <li>或者进行新的测试</li>
              </ul>
            </div>
          </template>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="filteredReports.length > 0">
      <div class="pagination-wrapper">
        <div class="page-size-selector">
          <span class="page-size-label">每页显示</span>
          <el-select
            v-model="pageSize"
            @change="handleSizeChange"
            size="default"
            style="width: 80px; margin: 0 8px"
          >
            <el-option
              v-for="size in [10, 20, 50, 100]"
              :key="size"
              :label="size"
              :value="size"
            />
          </el-select>
          <span class="page-size-label">条</span>
        </div>

        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :small="false"
          :disabled="false"
          :background="true"
          layout="prev, pager, next, jumper"
          :total="filteredReports.length"
          :pager-count="7"
          :hide-on-single-page="false"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error && !loading" class="error-message">
      <el-alert :title="error" type="error" :closable="false" show-icon />
    </div>
  </div>
</template>

<script>
import SvgIcon from '@/views/components/SvgIcon.vue'

import request from '@/utils/request'

export default {
  name: 'ReportsV2',
  components: {
    SvgIcon,
  },
  data() {
    return {
      reports: [],
      reportFilter: '',
      reportStatusFilter: 'all',
      loading: false,
      error: null,
      currentPage: 1,
      pageSize: 20,
    }
  },
  computed: {
    filteredReports() {
      let filtered = this.reports

      // 状态筛选
      if (this.reportStatusFilter !== 'all') {
        filtered = filtered.filter(
          (report) => report.status === this.reportStatusFilter,
        )
      }

      // 搜索筛选
      if (this.reportFilter.trim()) {
        const searchTerm = this.reportFilter.toLowerCase()
        filtered = filtered.filter(
          (report) =>
            (report.report_id || '').toLowerCase().includes(searchTerm) ||
            (report.device_id || '').toLowerCase().includes(searchTerm) ||
            (report.package_name || '').toLowerCase().includes(searchTerm),
        )
      }

      return filtered
    },
    paginatedReports() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredReports.slice(start, end)
    },
    completedCount() {
      return this.reports.filter((report) => report.status === 'completed')
        .length
    },
    runningCount() {
      return this.reports.filter((report) => report.status === 'running').length
    },
  },
  watch: {
    reportFilter() {
      this.currentPage = 1
    },
    reportStatusFilter() {
      this.currentPage = 1
    },
  },
  mounted() {
    this.fetchReports()
  },
  methods: {
    async fetchReports() {
      this.loading = true
      this.error = null
      try {
        const response = await request.get('/fastbot/reports')
        if (response.success) {
          this.reports = response.data.reports || []
        } else {
          this.error = response.message || '获取测试报告列表失败'
          this.$message.error(this.error)
        }
      } catch (error) {
        console.error('获取报告列表失败:', error)
        this.error = '获取测试报告列表失败，请刷新页面重试'
        this.$message.error(this.error)
      } finally {
        this.loading = false
      }
    },
    refreshReports() {
      this.fetchReports()
    },
    setReportStatusFilter(status) {
      this.reportStatusFilter = status
    },
    getStatusType(status) {
      switch (status) {
        case 'completed':
          return 'success'
        case 'running':
          return 'warning'
        case 'failed':
          return 'danger'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'completed':
          return '已完成'
        case 'running':
          return '运行中'
        case 'failed':
          return '失败'
        default:
          return '未知'
      }
    },
    getRowClassName({ row }) {
      if (row.crash_count > 0) {
        return 'danger-row'
      }
      return ''
    },
    handleRowClick(row) {
      this.viewReportDetail(row.report_id)
    },
    viewReportDetail(reportId) {
      console.log(reportId)
      if (!reportId) {
        this.$message.error('报告ID不存在')
        return
      }

      // 跳转到报告详情页面
      this.$router.push({
        name: 'ReportDetail',
        params: { id: reportId },
      })
    },
    handleCurrentChange(page) {
      this.currentPage = page
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
    },
  },
}
</script>

<style scoped>
/* 基础容器样式 */
.reports-container {
  padding: 20px;
  /* background: white; */
  min-height: calc(100vh - 74px);
  max-width: 100%;
  margin: 0;
  width: 100%;
}

/* 页面头部 */
.page-header {
  margin-bottom: 8px;
}

.page-header h3 {
  margin: 0;
  color: #303133;
  font-size: 22px;
  font-weight: 600;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  gap: 12px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.left-section h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.device-summary {
  padding: 2px 8px;
  /* background: #f0f7ff; */
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
}

.summary-text {
  color: #409eff;
  font-size: 12px;
  font-weight: 500;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.search-input {
  width: 300px;
}

.filter-buttons {
  flex-shrink: 0;
}

/* 统计信息样式 */
.device-stats {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  padding: 10px 14px;
  /* background: white; */
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
  height: 42px;
}

.stat-item {
  color: #606266;
  font-size: 14px;
}

.stat-number {
  font-weight: 600;
  margin-left: 4px;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.warning {
  color: #e6a23c;
}

.stat-number.total {
  color: #409eff;
}

/* 报告内容样式 */
.reports-content {
  /* background: white; */
  border-radius: 6px;
  border: 1px solid var(--el-border-color);
  overflow: hidden;
  margin-bottom: 12px;
  height: calc(100vh - 290px);
  position: relative;
}

/* 表格容器居中 */
.reports-content .el-table {
  margin: 0 auto;
}

/* 空状态样式 */
.empty-state {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  /* background: white; */
}

.empty-description {
  color: #909399;
  font-size: 14px;
  line-height: 1.6;
  text-align: center;
}

.empty-description p {
  margin: 8px 0;
}

.empty-description ul {
  margin: 12px 0;
  padding: 0;
  list-style: none;
  text-align: left;
  display: inline-block;
}

.empty-description li {
  margin: 4px 0;
  position: relative;
  padding-left: 16px;
}

.empty-description li::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #409eff;
}

/* 表格自定义样式 */
:deep(.el-table) {
  border-radius: 6px;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  /* background: #f1f1f1; */
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  /* background: #c1c1c1; */
  border-radius: 4px;
  transition: background 0.3s;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.el-table__header) {
  background-color: #f8f9fa;
}

:deep(.el-table__header th) {
  text-align: center !important;
  font-weight: 600;
  color: #303133;
}

:deep(.el-table__body td) {
  text-align: center !important;
}

:deep(.el-table__row:hover) {
  background-color: #f0f9ff;
  cursor: pointer;
}

:deep(.danger-row) {
  background-color: #fef0f0;
}

:deep(.danger-row:hover) {
  background-color: #fde2e2;
}

/* 表格单元格内容居中 */
:deep(.el-table .cell) {
  text-align: center;
}

/* 确保按钮等元素在表格中居中 */
:deep(.el-table__body .el-button) {
  margin: 0 auto;
}

:deep(.el-table__body .el-tag) {
  margin: 0 auto;
}

/* 覆盖率数字样式 */
.coverage-rate {
  display: inline-block;
  text-align: center;
  width: 100%;
  font-size: 14px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: flex-start;
  margin: 4px 0;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 24px;
  width: 100%;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-size-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.page-size-selector :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
  height: 32px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-wrapper :deep(.el-pager li) {
  min-width: 32px;
  height: 32px;
  line-height: 30px;
  border-radius: 6px;
  margin: 0 2px;
  font-weight: 500;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
}

.pagination-wrapper :deep(.el-pager li:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.el-pager li.is-active) {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev),
.pagination-wrapper :deep(.btn-next) {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
  font-weight: 500;
}

.pagination-wrapper :deep(.btn-prev:hover),
.pagination-wrapper :deep(.btn-next:hover) {
  color: #409eff;
  border-color: #409eff;
}

.pagination-wrapper :deep(.btn-prev:disabled),
.pagination-wrapper :deep(.btn-next:disabled) {
  color: #c0c4cc;
  background-color: #fff;
  border-color: var(--el-border-color);
  cursor: not-allowed;
}

/* 错误信息样式 */
.error-message {
  margin-top: 12px;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .reports-container {
    padding: 16px;
  }

  .page-header h3 {
    font-size: 20px;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .left-section,
  .right-section {
    flex-direction: column;
    gap: 12px;
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .filter-buttons {
    display: flex !important;
    flex-wrap: wrap;
    gap: 4px;
  }

  .device-stats {
    justify-content: center;
    text-align: center;
    height: auto;
    padding: 12px 14px;
  }

  /* 移动端报告列表高度调整 */
  .reports-content {
    height: calc(100vh - 240px);
  }

  .pagination-wrapper {
    flex-direction: column;
    gap: 16px;
  }

  .page-size-selector {
    order: 2;
  }
}

@media (max-width: 1024px) {
  .filter-buttons .el-button {
    font-size: 11px;
    padding: 6px 10px;
  }
}

@media (max-width: 480px) {
  .device-stats {
    flex-direction: column;
    gap: 8px;
    height: auto;
  }
}
</style> 